//
//  JXAccountCenterController.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/1/16.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  结算中心

#import "JXAccountCenterController.h"
#import "AccountCenterHeaderView.h"

#import "AccountCenterCell.h"
#import "AccountCenterButtonPriceBar.h"
#import "AccountCenterPayModeView.h"
#import "JXBaseRequest.h"
#import "CartDataTool.h"
#import "CartInfoDao.h"
#import "CartOrderStatusController.h"
#import "JXNavigationController.h"
#import "WXPayClient.h"
#import "AlipayUtil.h"
#import "TalkingDataAppCpa.h"
#import "JXAddressListController.h"
#import "JXVolumeCtrl.h"


@interface JXAccountCenterController ()<UITableViewDelegate,UITableViewDataSource,AccountCenterFooterViewDelegate,AccountCenterHeaderViewDelegate,AccountCenterButtonPriceBarDelegate,JXAddressListControllerDelegate>
{
    AccountCenterHeaderView *_headerView;
    AccountCenterFooterView *_footerView;
    TDOrder *_order;
}
@property(nonatomic,strong)AddressAndCheckProdInfo *info;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)AccountCenterButtonPriceBar *priceBar;
@property(nonatomic,strong)AddressDetail *defaultAddress;
@property(nonatomic,assign)NSInteger freight;;
@property(nonatomic,assign)int currentPayMode;;
@property(nonatomic,assign)accountCenterFinishType type;

@property(nonatomic,strong)Voucher *voucher;

//------------talkdata----------//

@property(nonatomic,assign) int total;//订单总金额，单位：分
/**
 *  订单支付方式 : alipay wxpay cargopay
 */
@property(nonatomic,copy) NSString *payType;

@property(nonatomic,copy) NSString *orderNum;
//------------talkdata----------//
@end

@implementation JXAccountCenterController

+(instancetype)initWithProdInfo:(AddressAndCheckProdInfo *)info :(accountCenterFinishType)type{
    JXAccountCenterController *result = [[JXAccountCenterController alloc]init];
    result.info = info;
    result.type = type;
    return result;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"结算中心"];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self regiestNotice];
    [self setupHeaderView];
    [self setupFooterView];
    [self setupTabView];
    [self setupPriceBar];
}

-(void)regiestNotice{
    //注册软键盘弹出隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    //注册支付状态的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(payStatusNotify:)name:@"pay_status" object:nil];
    //注册选择代金卷返回的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(backAccount:)name:@"account_voucher_notify" object:nil];
    //注册取消现金券的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(clickCancle:)name:@"account_voucher_cancle" object:nil];
}
/**
 *  初始化商品总价显示条
 */
-(void)setupPriceBar{
    _priceBar = [[AccountCenterButtonPriceBar alloc]init];
    _priceBar.x = 0;
    _priceBar.y = JXScreenH - 49;
    _priceBar.delegate = self;
    
    //设置价格+当前条件的邮费
    double price =_info.dprice.intValue;
    double spare = _info.price.intValue;
    if(_info.currentPayMode == PAYMODE_ALIPAY||_info.currentPayMode == PAYMODE_WXPAY){
        price = price + [[_footerView calcLinePayFreight:_info] freightNum];
        if(_info.currentPayMode == PAYMODE_ALIPAY){
            _currentPayMode = PAYMODE_ALIPAY;
        }
        if(_info.currentPayMode == PAYMODE_WXPAY){
            _currentPayMode = PAYMODE_WXPAY;
        }
    }else{
        _currentPayMode = PAYMODE_CARGO_PAY;
        price = price + [[_footerView calcCargoFreight:_info] freightNum];
    }
    [_priceBar setPriceNum:price + _freight];
    [_priceBar setSpareNum:spare];
    [_priceBar setPracticalPrice:price + _freight];
    //设置结算按钮是否要显示立即支付
    if(_info.isImmediatelyPay){
        [_priceBar setBtnText:@"立即支付"];
    }
    [self.view addSubview:_priceBar];
}

/**
 *  初始化headerView
 */
-(void)setupHeaderView{
    _headerView = [[AccountCenterHeaderView alloc]init];
    _headerView.x = 0;
    _headerView.y = 0;
    _headerView.delegate = self;
    if(_info){
        if(_info.addressInfo){//判断是否有地址信息
            [self setAddressInfo:_info.addressInfo.addressee phone:_info.addressInfo.phoneCode detail:_info.addressInfo.detailAdres];
        }else{
            [self setAddressInfo:@"" phone:@"请填写收件人信息" detail:@""];
        }
    }
}

/**
 *  初始化footerView
 */
-(void)setupFooterView{
    _footerView = [[AccountCenterFooterView alloc]init];
    _footerView.delegate = self;
    if(_info){
        [_footerView setInfos:_info];
//        [_footerView setVolumeText:[self getCanUseCount] price:0];
    }
}

/**
 *  初始化tabView
 */
- (void)setupTabView {
    _tableView = [[UITableView alloc]init];
    _tableView.frame = CGRectMake(0, 0, JXScreenW, JXScreenH-49);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor =[UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_tableView];
    //headerView
    [_tableView setTableHeaderView:_headerView];
    //footerView
    [_tableView setTableFooterView:_footerView];
}

/**
 *  设置地址信息
 *
 *  @param name   姓名
 *  @param phone  电话
 *  @param detail 详细地址
 */
-(void)setAddressInfo:(NSString *)name phone:(NSString *)phone detail:(NSString *)detail{
    [_headerView setAddressName:name];
    [_headerView setAddressPhone:phone];
    [_headerView setAddressDetail:detail];
}

/**
 *  跳转到支付状态页面
 */
- (void)toOrderStatusPage{
    JXLog(@"结算订单");
    [self addOrderParams];
    //结束输入，隐藏键盘
    [self.view.superview endEditing:YES];
}

/**
 * 组织订单数据，生成订单
 */
-(void)addOrderParams{
    
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    //备注信息
    NSString *userRemark = _footerView.getUserRemark;
    [params setObject:userRemark forKey:@"userRemark"];
    //地址id
    if(_defaultAddress){
        [params setObject:  _defaultAddress.addressId forKey:@"addressId"];
    }else{
        if(_info&&_info.addressInfo){
            [params setObject:_info.addressInfo.addressId forKey:@"addressId"];
        }
    }
    //订单号
    if(_info.orderCode){
        [params setObject:_info.orderCode forKey:@"orderCode"];
    }
    //价格
    [params setObject:_info.dprice forKey:@"dprice"];
    //运费和，支付方式
    [params setObject: [NSString stringWithFormat:@"%ld",(long)_freight]forKey:@"freight"];
    [params setObject:[NSString stringWithFormat:@"%d",_currentPayMode] forKey:@"payMode"];
    //现金券id
    if(_voucher!=nil){
        [params setObject:_voucher.vocherId forKey:@"voucherId"];
    }
    //判断如果有没有选择地址
    if(params[@"addressId"]){
        [self newOrder:params];
    }else{
        [DialogUtils showTipsWithView:self.view String:@"请选择收货地址"];
    }
}

/**
 *  生成订单
 *
 *  @param params
 */
-(void)newOrder:(NSMutableDictionary *)params{
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    [CartDataTool addOrderWithParam:params success:^(AddOrderRes *result) {
        [loding setHidden:YES];
        if([Utils isBlankString:result.data]){
            self.total = [result.money intValue] * 100;
            self.orderNum = result.orderNum;
            _order = [TDOrder orderWithOrderId:result.orderNum total:self.total currencyType:@"CNY"];
            [self assertPayMode:result];
        }else{
            [DialogUtils showTipsWithView:self.view String:result.data];
        }
    } failure:^(NSError *error) {
        [loding setHidden:YES];
        [DialogUtils showTipsWithView:self.view String:@"生成订单失败"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pay_status" object:@"4000"];
    }];
}

/**
 *  判断用什么方式去支付
 *
 *  @param result
 */
-(void)assertPayMode:(AddOrderRes *)result{
    switch (_currentPayMode) {
        case PAYMODE_CARGO_PAY://货到付款
            self.payType = @"cargopay";
            [[NSNotificationCenter defaultCenter] postNotificationName:@"pay_status" object:@"9000"];
            break;
        case PAYMODE_ALIPAY://调用支付宝支付
            self.payType = @"alipay";
            [[[AlipayUtil alloc]init] callPay:result.orderNum prodName:result.prodName prodDetail:result.prodDetail money:result.money notify_url:result.notifyUrl showProdUrl:result.showProdUrl];
            break;
        case PAYMODE_WXPAY://调用微信支付
            self.payType = @"wxpay";
            [[[WXPayClient alloc]init] pay:result.orderNum prodName:result.prodName money:result.money notifyUrl:result.notifyUrl container:self.view];
            break;
        default:
            break;
    }
}

/**
 *  支付结果通知
 */
-(void)payStatusNotify:(NSNotification*)aNotification {
    NSString *status = [aNotification object];
    [self.navigationController popViewControllerAnimated:NO];
    [self assertToType:status];
    
    JXLog(@"%@",status);
}

-(void)comitTalkDataWithPayStatus:(NSString *)status{
    if ([status isEqualToString:@"9000"]) {
        //代表支付成功
        [TalkingDataAppCpa onOrderPaySucc:[UserDefaultsHelper stringForKey:KEY_USER_ID] withOrderId:self.orderNum withAmount:self.total withCurrencyType:@"CNY" withPayType:self.payType];
    }
}

/**
 *  判断回调那个页面
 *
 *  @param status 订单状态
 */
-(void)assertToType:(NSString *)status{
    switch (_type) {
        case ACCOUNT_CENTER_CART_FINISH://回调购物车
            [_delegate accountCenterFinish:ACCOUNT_CENTER_CART_FINISH status:status];
            break;
        case ACCOUNT_CENTER_ORDER_DETAIL://回调订单详情
            [_delegate accountCenterFinish:ACCOUNT_CENTER_ORDER_DETAIL status:status];
        case ACCOUNT_CENTER_ORDER_LIST://回调订单列表
            [_delegate accountCenterFinish:ACCOUNT_CENTER_ORDER_LIST status:status];
            break;
            
        default:
            break;
    }
}

/**
 *  跳转到选择地址页面
 */
-(void)checkAddress{
    JXAddressListController *ctrl = [[JXAddressListController alloc]init];
    ctrl.delegate = self;
    ctrl.fromAccountCenter = YES;
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(void)setAddressDetailInfo:(AddressDetail *)detail{
    //1.跳转到选择地址页面，选择地址拿到数据后，调用 [self setAddressInfo:@"姓名" phone:@"请填写收件人信息" detail:@"地址"];
    //2.defaultAddress
    [self setAddressInfo:detail.addressee phone:detail.phoneCode detail:detail.detailAdres2];
    _defaultAddress = detail;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //判断没有数据就不显示表格线，有数据则显示
    if(self.info.prodList.count){
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else{
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self.info.prodList.count;
}

/**
 *  选择支付方式回调
 *
 *  @param payMode
 */
-(void)selectPayMode:(NSInteger)payMode{
    
    switch (payMode) {
        case PAYMODE_CARGO_PAY:
            _currentPayMode = PAYMODE_CARGO_PAY;
            _freight = [[_footerView calcCargoFreight:_info] freightNum];
            if(_info.isImmediatelyPay){
                [_priceBar setBtnText:@"提交订单"];
            }
            break;
        case PAYMODE_ALIPAY:
            _currentPayMode = PAYMODE_ALIPAY;
            _freight = [[_footerView calcLinePayFreight:_info] freightNum];
            if(_info.isImmediatelyPay){
                [_priceBar setBtnText:@"立即支付"];
            }
            break;
        case PAYMODE_WXPAY:
            _currentPayMode = PAYMODE_WXPAY;
            _freight = [[_footerView calcLinePayFreight:_info] freightNum];
            if(_info.isImmediatelyPay){
                [_priceBar setBtnText:@"立即支付"];
            }
            break;
        default:
            break;
    }
    
    //更改底部栏的数据
    [_priceBar setPriceNum:_info.dprice.integerValue + _freight];
    [_priceBar setPracticalPrice:_info.dprice.integerValue + _freight];
}

/**
 *  点击选择代金卷
 */
-(void)clickVolume{
    JXVolumeCtrl *ctrl;
    if(_voucher == nil){//还未选择现金券,允许再次选择,YES
       ctrl = [JXVolumeCtrl initWithPrice:_info.voucherList prodPrice:_info.dprice.intValue isChoice:YES type:ACCOUNT_TYPE];
    }else{//已选择现金券,不让再次选择,NO
       ctrl = [JXVolumeCtrl initWithPrice:_info.voucherList prodPrice:_info.dprice.intValue isChoice:NO type:ACCOUNT_TYPE];
    }
    [self.navigationController pushViewController:ctrl animated:YES];
}

/**
 *  选完现金券回调
 */
-(void)backAccount:(NSNotification*)aNotification{
     _voucher = [aNotification object];
    [_footerView setVolumeText:_voucher.amount.intValue price:_voucher.amount.intValue];
    [self checkPayModeChangeFreight:NO];
}

/**
 *  根据当前的支付方式，判断选取现金券后重新计算邮费，（是否满足包邮条件）
 */
-(void)checkPayModeChangeFreight:(BOOL)isCancle{
    switch (_currentPayMode) {
        case PAYMODE_CARGO_PAY:
            _freight = [[_footerView calcCargoFreight:_info] freightNum];
            break;
        case PAYMODE_ALIPAY:
            _freight = [[_footerView calcLinePayFreight:_info] freightNum];
            break;
        case PAYMODE_WXPAY:
            _freight = [[_footerView calcLinePayFreight:_info] freightNum];
            break;
        default:
            break;
    }
    
    [_priceBar setPriceNum:_info.dprice.intValue + _freight];
    [_priceBar setSpareNum:_info.price.intValue + _voucher.amount.intValue];
    
    if(isCancle)
     [_priceBar setPracticalPrice:_info.dprice.intValue+_freight+_voucher.amount.intValue];
    else
     [_priceBar setPracticalPrice:_info.dprice.intValue+_freight-_voucher.amount.intValue];
}

/**
 *  取消代金卷
 */
-(void)clickCancle:(NSNotification*)aNotification{
    [_footerView setVolumeText:[self getCanUseCount] price:0];
    _voucher = nil;
    //还原总价之后重新计算邮费等数据并设置
    [self checkPayModeChangeFreight:YES];
}

/**
 *  获取可以使用的代金卷张数
 *
 *  @return
 */
-(int)getCanUseCount{
    int canUseCount = 0;
    NSInteger count  = _info.voucherList.count;
    for (int i = 0; i < count; i++) {
        if([_info.voucherList[i] isPast] == 0 && [_info.voucherList[i] useAmount].intValue < _info.dprice.intValue){
            canUseCount++;
        }
    }
    return canUseCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AccountCenterCell *cell = [AccountCenterCell cellWithTableView:tableView];
    [cell setCartInfos:self.info.prodList[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //处理cell点击效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [DimensUtils getScaleX:57];
}

-(void)viewDidLayoutSubviews
{
    //改变分割线的样式
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,56,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,56,0,0)];
    }
}

-(void)scrollViewWillBeginDragging:(UITableView *)tabview{
    [self.view.superview endEditing:YES];
}

//键盘显示的广播
- (void) keyboardWillShow:(NSNotification *)notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    [UIView animateWithDuration:0.3 delay:0 options:0 animations:^{
        //出现两次弹出的问题，用0去减
        self.view.y = 0 - keyboardSize.height;
    } completion:^(BOOL finished) {}];
}

//键盘隐藏的广播
-(void)keyboardWillHide:(NSNotification*)notif
{
    [UIView animateWithDuration:0.2 delay:0 options:0 animations:^{
        self.view.y = 0;
    } completion:^(BOOL finished) {}];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
